/* eslint-disable max-lines */
import React from 'react';
import PropTypes from 'prop-types';
import {Card, Button, Row, Col, Form, Spin, Table, Popconfirm, message as msg, Switch, Input} from 'antd';
import TextInput from 'Shared/components/TextInput';
import routes from './routes';
import {updateValidator} from './validator';
import Return from '../common/Return';
import {FORM_OPTIONS, TABLE, FIXED_COLUMN_WIDTH, PAGE} from '../constants';
import {getDetail, updateData} from './api';
import {agentKind, priceClause, currency, palletizing, invoiceTemplateType} from '../Enum';
import styles from './style.css';
import {conventEnumValueToString} from '../utils';
import WrappedSelect from '../common/WrappedSelect';
import {uuid} from './utils';
import SearchInput from 'Shared/components/SearchInput';
import BankSelectPanel from './BankSelectPanel';
import PartSelectPanel from './PartSelectPanel';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import LocalizeInputNumber from '../common/LocalizeInputNumber';
import InputPercent from '../common/InputPercent';
import DealerSelectPanel from './DealerSelectPanel';
import ImportPanel from './ImportPanel';
import {injectIntl, language} from './intl';
import Export from '../common/Export';

const {Search} = Input;
const FormItem = Form.Item;
const priceClauseList = priceClause.toList(language);
const currencyList = currency.toList(language);
const palletizingList = palletizing.toList(language);
const invoiceTemplateTypeList = invoiceTemplateType.toList(language);

export class UpdatePanel extends React.PureComponent {
    state = {
        isValidate: false,
        hasOperat: false,
        loading: false,
        showDealerSelectPanel: false,
        showBankSelectPanel: false,
        showPartSelectPanel: false,
        detailId: '',
        data: {},
        dealerParts: [],
        dealerBanks: [],
        parts: [],
        showImportPanel: false,
        detailPagination: {
            pageIndex: PAGE.index,
            pageSize: 100,
            sortedColumnKey: 'code',
            sortedOrder: true,
        },
        updateParts: [],
        isClearPart: false,
        searchPartCode: '',
        newParts: [],
        isSearch: false
    }
   
    componentDidMount() {
        if(this.props.id)
            this.getDetailInfo();
    }
    componentWillUnmount() {
        this.isunmount = true;
    }
    getDetailInfo = () => {
        const id = this.props.id;
        this.setState({loading: true});
        getDetail(id)
            .then(res => {
                if(res.ok)
                    this.setState({
                        loading: false,
                        data: res.data,
                        dealerParts: res.data.dealerParts,
                        dealerBanks: res.data.dealerBanks,
                        parts: res.data.parts
                    });
                else
                    this.setState(({
                        loading: false
                    }));
            });
    }
    onSubmit = () => {
        this.setState({
            loading: true
        });
        const {data, dealerParts, dealerBanks, updateParts, isClearPart} = this.state;
        const bankIds = [];
        if(dealerBanks)
            for(const d of dealerBanks)
                bankIds.push(d.bankId);
        // if(updateParts)
        //     for(const p of updateParts)
        //         partIds.push(p.partId);
        const condition = {
            rowVersion: data.rowVersion,
            dealerParts: (dealerParts || []).map(v => ({
                brandId: v.brandId,
                tradeMethodId: v.tradeMethodId,
                arrivedDealerId: v.arrivedDealerId,
                priceClause: v.priceClause,
                isSeparate: v.isSeparate,
                isPlaned: v.isPlaned,
                planedStartDate: v.planedStartDate,
                planedEndDate: v.planedEndDate,
                currency: v.currency,
                labelRequirement: v.labelRequirement,
                palletizing: v.palletizing,
                shippingMark: v.shippingMark,
                isClaim: v.isClaim,
                mgmtRate: v.mgmtRate,
                remark: v.remar,
                invoiceTemplateType: v.invoiceTemplateType
            })),
            dealerBanks: bankIds,
            parts: updateParts,
            isClearPart
        };

        const isValid = updateValidator(condition);
        if(!isValid) {
            this.setState({
                isValidate: true,
                loading: false
            });
            return;
        }
        updateData(data.id, condition).then(res => {
            if(res.ok)
                this.props.successReturn();
            if(!this.isunmount)
                this.setState({loading: false});
        });
    }
    onClickReturnBtn = () => {
        this.props.onCancel();
    }
    onClickAddDetailBtn = () => {
        const details = this.state.dealerParts;
        this.setState({
            dealerParts: [
                ...details,
                {
                    id: uuid(),
                    isPlaned: false,
                    isSeparate: false,
                    isClaim: false
                }
            ],
            hasOperat: true
        });
    };
    onBrandChange = (brandId, id) => {
        const details = this.state.dealerParts || [];
        const index = details.findIndex(v => v.brandId === brandId);
        if(index === 0)
            return msg.warn(this.props.intl.formatMessage({
                id: 'updatePanel.message.brand',
                defaultMessage: '已存在该品牌'
            }));
        const tmp = details.map(d => {
            const index = details.findIndex(v => v.brandId === brandId);
            if(d.id === id && index === -1)
                return Object.assign({}, d, {
                    brandId,
                });
            return d;
        });
        this.setState({
            dealerParts: tmp,
            hasOperat: true
        });
    }
    onTradeMethodChange = (tradeMethodId, id) => {
        const details = this.state.dealerParts || [];
        const tmp = details.map(d => {
            if(d.id === id)
                return Object.assign({}, d, {
                    tradeMethodId,
                });
            return d;
        });
        this.setState({
            dealerParts: tmp,
            hasOperat: true
        });
    }
    onDealerPartInformationChange = (value, name, id) => {
        const details = this.state.dealerParts || [];
        const tmp = details.map(d => {
            if(d.id === id)
                if(name === 'isPlaned')
                    return Object.assign({}, d, {
                        [name]: value,
                        planedStartDate: null,
                        planedEndDate: null
                    });
                else
                    return Object.assign({}, d, {
                        [name]: value,
                    });
            return d;
        });
        this.setState({
            dealerParts: tmp,
            hasOperat: true
        });
    }
    onDeleteDetail = e => {
        const id = e.target.dataset.id;
        const dealerParts = this.state.dealerParts.filter(p => p.id !== id);
        this.setState({
            dealerParts,
            hasOperat: true
        });
    }
    onDeleteAll = () => {
        this.setState({
            dealerParts: [],
            hasOperat: true
        });
    }
    onSelectDealer = record => {
        const details = this.state.dealerParts || [];
        const tmp = details.map(d => {
            if(d.id === this.state.detailId)
                return Object.assign({}, d, {
                    arrivedDealerId: record.id,
                    arrivedDealerCode: record.code,
                    arrivedDealerName: record.name
                });
            return d;
        });
        this.setState({
            showDealerSelectPanel: false,
            dealerParts: tmp,
            hasOperat: true
        });
    }
    onClickSearchDealerBtn = id => {
        this.setState({
            showDealerSelectPanel: true,
            detailId: id
        });
    }
    onCloseDealerSelectPanel= () => {
        this.setState({showDealerSelectPanel: false});
    }
    onClickSearchBankBtn = () => {
        this.setState({
            showBankSelectPanel: true,
        });
    }
    onBankDeleteAddedItem = e => {
        const addedItemId = e.target.dataset.id;
        const tmp = this.state.dealerBanks.filter(d => d.bankId !== addedItemId);
        this.setState({
            dealerBanks: [...tmp],
            hasOperat: true
        });
    }
    onBankDeleteAll = () => {
        this.setState({
            dealerBanks: [],
            hasOperat: true
        });
    }
    onCloseBankSelectPanel = () => {
        this.setState({showBankSelectPanel: false});
    }
    onSelectAddedBank = records => {
        const addedItems = this.state.dealerBanks || [];
        records.forEach(r => {
            const index = addedItems.findIndex(v => v.bankId === r.id);
            if(index === -1)
                addedItems.push({
                    bankId: r.id,
                    bankCode: r.code,
                    bankName: r.name,
                });
        });
        this.setState({
            dealerBanks: [...addedItems],
            hasOperat: true,
            showBankSelectPanel: false
        });
    }
    onPartDeleteAddedItem = e => {
        const addedItemId = e.target.dataset.id;
        const tmp = this.state.parts.filter(d => d.partId !== addedItemId);
        const updateParts = this.state.updateParts || [];
        const updateIndex = updateParts.findIndex(v => v.partId === addedItemId);
        if(this.state.isSearch) {
            const tmp = this.state.newParts.filter(d => d.partId !== addedItemId);
            this.setState({
                newParts: [...tmp]
            });
        }
        if(updateIndex === -1) {
            updateParts.push({
                partId: addedItemId,
                isUpdate: false
            });
            this.setState({
                parts: [...tmp],
                updateParts: [...updateParts],
                hasOperat: true
            });
        } else {
            const update = this.state.updateParts.map(v => {
                if(v.partId === addedItemId)
                    return Object.assign({}, v, {
                        isUpdate: false
                    });
                return v;
            });
            this.setState({
                parts: [...tmp],
                updateParts: update,
                hasOperat: true
            });
        }
    }
    onPartDeleteAll = () => {
        const updateParts = this.state.updateParts || [];
        const tmp = updateParts.map(v => Object.assign({}, v, {
            isUpdate: false
        }));
        this.setState({
            parts: [],
            newParts: [],
            isClearPart: true,
            updateParts: tmp,
            hasOperat: true
        });
    }
    onClosePartSelectPanel = () => {
        this.setState({showPartSelectPanel: false});
    }
    onSelectAddedPart = records => {
        const addedItems = this.state.parts || [];
        const addNewPartItems = this.state.newParts || [];
        const updateParts = this.state.updateParts || [];
        const updateStatus = [];
        records.forEach(r => {
            const index = addedItems.findIndex(v => v.partId === r.id);
            const indexNew = addNewPartItems.findIndex(v => v.partId === r.id);
            const updateIndex = updateParts.findIndex(v => v.partId === r.id);
            if(indexNew === -1 && this.state.isSearch)
                addNewPartItems.push({
                    partId: r.id,
                    partCode: r.code,
                    partName: r.name,
                });
            if(index === -1) {
                addedItems.push({
                    partId: r.id,
                    partCode: r.code,
                    partName: r.name,
                });
                if(updateIndex === -1)
                    updateParts.push({
                        partId: r.id,
                        isUpdate: true
                    });
                else updateStatus.push({
                    partId: r.id,
                    isUpdate: true
                });
            }
            if(r.partReplacements.length === 1) {
                const partReplacement = r.partReplacements[0];
                const index = addedItems.findIndex(v => v.partId === partReplacement.id);
                const updateIndex = updateParts.findIndex(v => v.partId === partReplacement.id);
                
                const indexNew = addNewPartItems.findIndex(v => v.partId === r.id);
                if(indexNew === -1 && this.state.isSearch)
                    // eslint-disable-next-line array-callback-return
                    r.partReplacements.map(item => {
                        addNewPartItems.push({
                            partId: item.id,
                            partCode: item.code,
                            partName: item.name
                        });
                    });
                if(index === -1)
                    // eslint-disable-next-line array-callback-return
                    r.partReplacements.map(item => {
                        addedItems.push({
                            partId: item.id,
                            partCode: item.code,
                            partName: item.name
                        });
                        if(updateIndex === -1)
                            updateParts.push({
                                partId: item.id,
                                isUpdate: true
                            });
                        else updateStatus.push({
                            partId: item.id,
                            isUpdate: true
                        });
                    });
            }
        });
        const temp = updateParts.map(v => {
            const index = updateStatus.findIndex(o => o.partId === v.partId);
            if(index === -1)
                return v;
            return Object.assign({}, v, {
                isUpdate: true
            });
        });
        this.setState({
            parts: [...addedItems],
            newParts: this.state.isSearch ? [...addNewPartItems] : [],
            updateParts: [...temp],
            hasOperat: true,
            showPartSelectPanel: false
        });
    }
    onClickSearchPartBtn = () => {
        this.setState({
            showPartSelectPanel: true,
        });
    }
    onClickImportBtn = () => {
        this.setState({
            showImportPanel: true
        });
    }
    onCloseImportPanel = () => {
        this.setState({showImportPanel: false});
    }
    onImportChange = records => {
        const addedItems = this.state.parts || [];
        const updateParts = this.state.updateParts || [];
        const updateStatus = [];
        records.payload.content.forEach(r => {
            const index = addedItems.findIndex(v => v.partId === r.id);
            const updateIndex = updateParts.findIndex(v => v.partId === r.id);
            if(index === -1) {
                addedItems.push({
                    partId: r.partId,
                    partCode: r.partCode,
                    partName: r.partName,
                });
                if(updateIndex === -1)
                    updateParts.push({
                        partId: r.partId,
                        isUpdate: true
                    });
                else updateStatus.push({
                    partId: r.partId,
                    isUpdate: true
                });
            }
        });
        const temp = updateParts.map(v => {
            const index = updateStatus.findIndex(o => o.partId === v.partId);
            if(index === -1)
                return v;
            return Object.assign({}, v, {
                isUpdate: true
            });
        });
        this.setState({
            parts: [...addedItems],
            newParts: this.state.isSearch ? [...addedItems] : [],
            updateParts: [...temp],
            hasOperat: true,
            showImportPanel: false
        });
    }
    onChangeDetail = (pagination, filters, sorter) => {
        this.setState({
            detailPagination: {
                pageIndex: pagination.current - 1,
                pageSize: pagination.pageSize,
                sortedColumnKey: sorter.columnKey,
                sortedOrder: sorter.order,
            }
        });
    };
    onSearchClaim = value => {
        const {parts} = this.state;
        if(!parts.length)
            return msg.warn(this.props.intl.formatMessage({
                id: 'updatePanel.onClickSearchDetail.message',
                defaultMessage: '请先增加清单'
            }));
        this.setState({
            newParts: parts.filter(v => v.partCode.includes(value)),
            isSearch: true
        });
    }
    onChangeCodeValue = e => {
        this.setState({
            searchPartCode: e.target.value
        });
        if(!e.target.value)
            this.setState({
                isSearch: false,
                newDetails: []
            });
    }
    render() {
        const {data, dealerParts, dealerBanks, parts, isValidate,
            detailPagination, updateParts, isClearPart, isSearch, newParts} = this.state;
        const {formatMessage} = this.props.intl;
        const {brands, tradeMethods} = this.props.initEnumData;
        const partInformationColumns = [{
            title: (<span className="ant-form-item-required">{formatMessage({
                id: 'updatePanel.column.brand',
                defaultMessage: '品牌'
            })}</span>
            ),
            width: 150,
            dataIndex: 'brandId',
            render: (text, record) => {
                const validate = !text && isValidate ? {validateStatus: 'error'} : null;
                return (
                    <FormItem {...validate}>
                        <WrappedSelect
                            id={record.id}
                            options={brands}
                            value={record.brandId}
                            onChange={this.onBrandChange} />
                    </FormItem>
                );
            }
        }, {
            title: (<span className="ant-form-item-required">{formatMessage({
                id: 'updatePanel.column.tradeMethod',
                defaultMessage: '贸易方式'
            })}</span>
            ),
            width: 150,
            dataIndex: 'tradeMethodId',
            render: (text, record) => {
                const validate = !text && isValidate ? {validateStatus: 'error'} : null;
                return (
                    <FormItem {...validate}>
                        <WrappedSelect
                            id={record.id}
                            options={tradeMethods}
                            value={record.tradeMethodId}
                            onChange={this.onTradeMethodChange} />
                    </FormItem>
                );
            }
        }, {
            title: (<span className="ant-form-item-required">{formatMessage({
                id: 'updatePanel.column.arrivedDealer',
                defaultMessage: '送达方'
            })}</span>
            ),
            dataIndex: 'arrivedDealerId',
            render: (text, record) => {
                const validate = !text && isValidate ? {validateStatus: 'error'} : null;
                return (
                    <FormItem {...validate}>
                        <SearchInput
                            disabled={true}
                            value={record.arrivedDealerId ? `(${record.arrivedDealerCode}) ${record.arrivedDealerName}` : ''}
                            onClickSearchBtn={() => this.onClickSearchDealerBtn(record.id)} />
                    </FormItem>
                );
            }
        }, {
            title: (<span className="ant-form-item-required">{formatMessage({
                id: 'updatePanel.column.priceClause',
                defaultMessage: '价格条款'
            })}</span>
            ),
            width: 120,
            dataIndex: 'priceClause',
            render: (text, record) => {
                const validate = !text && isValidate ? {validateStatus: 'error'} : null;
                return (
                    <FormItem {...validate}>
                        <WrappedSelect
                            id={record.id}
                            options={priceClauseList}
                            value={record.priceClause}
                            onChange={value => this.onDealerPartInformationChange(value, 'priceClause', record.id)}/>
                    </FormItem>
                );
            }
        }, {
            title: (<span className="ant-form-item-required">{formatMessage({
                id: 'updatePanel.column.isSeparate',
                defaultMessage: '商检分开打包'
            })}</span>
            ),
            dataIndex: 'isSeparate',
            render: (text, record) => (
                <Switch
                    checkedChildren={formatMessage({
                        id: 'yes',
                        defaultMessage: '是'
                    })}
                    unCheckedChildren={formatMessage({
                        id: 'no',
                        defaultMessage: '否'
                    })}
                    checked={text}
                    value={record.isSeparate}
                    id={record.id}
                    onChange={value => this.onDealerPartInformationChange(value, 'isSeparate', record.id)}/>
            )
        }, {
            title: (<span className="ant-form-item-required">{formatMessage({
                id: 'updatePanel.column.isPlaned',
                defaultMessage: '是否计划需求上报'
            })}</span>
            ),
            dataIndex: 'isPlaned',
            render: (text, record) => (
                <Switch
                    checkedChildren={formatMessage({
                        id: 'yes',
                        defaultMessage: '是'
                    })}
                    unCheckedChildren={formatMessage({
                        id: 'no',
                        defaultMessage: '否'
                    })}
                    checked={text}
                    value={record.isPlaned}
                    id={record.id}
                    onChange={value => this.onDealerPartInformationChange(value, 'isPlaned', record.id)}/>
            )
        }, {
            title: formatMessage({
                id: 'updatePanel.column.planedStartDate',
                defaultMessage: '计划需求开始日'
            }),
            dataIndex: 'planedStartDate',
            render: (text, record) => {
                const validate = !text && record.isPlaned === true ? {validateStatus: 'error'} : null;
                return (
                    <FormItem {...validate}>
                        <LocalizeInputNumber
                            disabled={record.isPlaned !== true}
                            name="planedStartDate"
                            min={1}
                            max={31}
                            value={record.planedStartDate}
                            onChange={value => this.onDealerPartInformationChange(value, 'planedStartDate', record.id)}/>
                    </FormItem>
                );
            }
        }, {
            title: formatMessage({
                id: 'updatePanel.column.planedEndDate',
                defaultMessage: '计划需求结束日'
            }),
            dataIndex: 'planedEndDate',
            render: (text, record) => {
                const validate = !text && record.isPlaned === true ? {validateStatus: 'error'} : null;
                return (
                    <FormItem {...validate}>
                        <LocalizeInputNumber
                            disabled={record.isPlaned !== true}
                            name="planedEndDate"
                            min={1}
                            max={31}
                            value={record.planedEndDate}
                            onChange={value => this.onDealerPartInformationChange(value, 'planedEndDate', record.id)}/>
                    </FormItem>
                );
            }
        }, {
            title: (<span className="ant-form-item-required">{formatMessage({
                id: 'updatePanel.column.currency',
                defaultMessage: '结算币种'
            })}</span>
            ),
            width: 100,
            dataIndex: 'currency',
            render: (text, record) => {
                const validate = !text && isValidate ? {validateStatus: 'error'} : null;
                return (
                    <FormItem {...validate}>
                        <WrappedSelect
                            id={record.id}
                            options={currencyList}
                            value={record.currency}
                            onChange={value => this.onDealerPartInformationChange(value, 'currency', record.id)}/>
                    </FormItem>
                );
            }
        }, {
            title: formatMessage({
                id: 'updatePanel.column.mgmtRate',
                defaultMessage: '备件管理费率'
            }),
            dataIndex: 'mgmtRate',
            render: (text, record) => (
                <InputPercent value={record.mgmtRate} precision={3}
                    onChange={value => this.onDealerPartInformationChange(value, 'mgmtRate', record.id)}/>
            )
        }, {
            title: formatMessage({
                id: 'updatePanel.column.labelRequirement',
                defaultMessage: '标签要求'
            }),
            dataIndex: 'labelRequirement',
            render: (text, record) => (
                <TextInput
                    value={record.labelRequirement}
                    onBlur={value => this.onDealerPartInformationChange(value, 'labelRequirement', record.id)}/>
            )
        }, {
            title: formatMessage({
                id: 'updatePanel.column.palletizing',
                defaultMessage: '托盘要求'
            }),
            width: 120,
            dataIndex: 'palletizing',
            render: (text, record) => (
                <FormItem>
                    <WrappedSelect
                        allowClear
                        id={record.id}
                        options={palletizingList}
                        value={record.palletizing}
                        onChange={value => this.onDealerPartInformationChange(value, 'palletizing', record.id)}/>
                </FormItem>
            )
        }, {
            title: formatMessage({
                id: 'updatePanel.column.shippingMark',
                defaultMessage: '唛头'
            }),
            dataIndex: 'shippingMark',
            render: (text, record) => (
                <TextInput
                    value={record.shippingMark}
                    onBlur={value => this.onDealerPartInformationChange(value, 'shippingMark', record.id)}/>
            )
        }, {
            title: (<span className="ant-form-item-required">{formatMessage({
                id: 'updatePanel.column.isClaim',
                defaultMessage: '是否备件索赔判定'
            })}</span>
            ),
            dataIndex: 'isClaim',
            render: (text, record) => (
                <Switch
                    checkedChildren={formatMessage({
                        id: 'yes',
                        defaultMessage: '是'
                    })}
                    unCheckedChildren={formatMessage({
                        id: 'no',
                        defaultMessage: '否'
                    })}
                    checked={text}
                    value={record.isClaim}
                    id={record.id}
                    onChange={value => this.onDealerPartInformationChange(value, 'isClaim', record.id)}/>
            )
        }, {
            title: formatMessage({
                id: 'updatePanel.column.remark',
                defaultMessage: '包装要求备注'
            }),
            dataIndex: 'remark',
            render: (text, record) => (
                <TextInput
                    value={record.remark}
                    onBlur={value => this.onDealerPartInformationChange(value, 'remark', record.id)}/>
            )
        }, {
            title: formatMessage({
                id: 'updatePanel.column.invoiceTemplateType',
                defaultMessage: '发票模板类型'
            }),
            width: 120,
            dataIndex: 'invoiceTemplateType',
            render: (text, record) => (
                <FormItem>
                    <WrappedSelect
                        allowClear
                        id={record.id}
                        options={invoiceTemplateTypeList}
                        value={record.invoiceTemplateType}
                        onChange={value => this.onDealerPartInformationChange(value, 'invoiceTemplateType', record.id)}/>
                </FormItem>
            )
        }, {
            title: dealerParts && dealerParts.length > 0
                ? (
                    <Popconfirm placement="topRight" title={formatMessage({
                        id: 'updatePanel.validation.isDelete',
                        defaultMessage: '是否确认全部删除？'
                    })} onConfirm={this.onDeleteAll} >
                        <a>{formatMessage({
                            id: 'updatePanel.validation.clear',
                            defaultMessage: '清空'
                        })}</a>
                    </Popconfirm>
                )
                : null,
            dataIndex: 'id',
            fixed: 'right',
            width: FIXED_COLUMN_WIDTH,
            render: text => <a data-id={text} onClick={this.onDeleteDetail}>{formatMessage({
                id: 'updatePanel.validation.delete',
                defaultMessage: '删除'
            })}</a>
        }];

        const bankColumns = [{
            title: formatMessage({
                id: 'updatePanel.column.bankCode',
                defaultMessage: '编号'
            }),
            dataIndex: 'bankCode',
        }, {
            title: formatMessage({
                id: 'updatePanel.column.bankName',
                defaultMessage: '名称'
            }),
            dataIndex: 'bankName',
        }, {
            title: dealerBanks && dealerBanks.length ? (
                <WrappedPopconfirm
                    id="updatePanel.bank.delete"
                    title={this.props.intl.formatMessage({
                        id: 'updatePanel.popconfirm.message',
                        defaultMessage: '是否继续?'
                    })}
                    okText={this.props.intl.formatMessage({
                        id: 'updatePanel.bank.popconfirm.confirm',
                        defaultMessage: '确认'
                    })}
                    cancelText={this.props.intl.formatMessage({
                        id: 'updatePanel.bank.popconfirm.cancel',
                        defaultMessage: '取消'
                    })}
                    onConfirm={this.onBankDeleteAll}>
                    <a>
                        {this.props.intl.formatMessage({
                            id: 'updatePanel.bank.deleteAll',
                            defaultMessage: '清空'
                        })}
                    </a>
                </WrappedPopconfirm>
            ) : null,
            dataIndex: 'action',
            fixed: 'right',
            width: FIXED_COLUMN_WIDTH,
            render: (text, record) => (
                <a onClick={this.onBankDeleteAddedItem} data-id={record.bankId}>
                    {this.props.intl.formatMessage({
                        id: 'updatePanel.bank.delete',
                        defaultMessage: '删除'
                    })}
                </a>
            )
        }];

        const partColumns = [{
            title: formatMessage({
                id: 'updatePanel.column.partCode',
                defaultMessage: '编号'
            }),
            dataIndex: 'partCode',
        }, {
            title: formatMessage({
                id: 'updatePanel.column.partName',
                defaultMessage: '名称'
            }),
            dataIndex: 'partName',
        }, {
            title: parts && parts.length ? (
                <WrappedPopconfirm
                    id="updatePanel.bank.delete"
                    title={this.props.intl.formatMessage({
                        id: 'updatePanel.part.popconfirm.message',
                        defaultMessage: '是否继续?'
                    })}
                    okText={this.props.intl.formatMessage({
                        id: 'updatePanel.part.popconfirm.confirm',
                        defaultMessage: '确认'
                    })}
                    cancelText={this.props.intl.formatMessage({
                        id: 'updatePanel.part.popconfirm.cancel',
                        defaultMessage: '取消'
                    })}
                    onConfirm={this.onPartDeleteAll}>
                    <a>
                        {this.props.intl.formatMessage({
                            id: 'updatePanel.part.deleteAll',
                            defaultMessage: '清空'
                        })}
                    </a>
                </WrappedPopconfirm>
            ) : null,
            dataIndex: 'action',
            fixed: 'right',
            width: FIXED_COLUMN_WIDTH,
            render: (text, record) => (
                <a onClick={this.onPartDeleteAddedItem} data-id={record.partId}>
                    {this.props.intl.formatMessage({
                        id: 'updatePanel.part.delete',
                        defaultMessage: '删除'
                    })}
                </a>
            )
        }];

        return (
            <div>
                <Spin spinning={this.state.loading}>
                    <Form className="form-standard">
                        <Card title={formatMessage({
                            id: 'addPanel.card.title',
                            defaultMessage: '基本信息'
                        })}>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'updatePanel.data.code',
                                        defaultMessage: '编号'
                                    })}{...FORM_OPTIONS.item} >
                                        {data.code}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'updatePanel.data.name',
                                        defaultMessage: '名称'
                                    })}{...FORM_OPTIONS.item} >
                                        {data.name}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'updatePanel.data.shortCode',
                                        defaultMessage: '简码'
                                    })}{...FORM_OPTIONS.item} >
                                        {data.shortCode}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'updatePanel.data.shortName',
                                        defaultMessage: '简称'
                                    })}{...FORM_OPTIONS.item} >
                                        {data.shortName}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'updatePanel.data.kind',
                                        defaultMessage: '客户分类'
                                    })}{...FORM_OPTIONS.item} >
                                        {conventEnumValueToString(agentKind, data.kind)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'updatePanel.data.country',
                                        defaultMessage: '国家'
                                    })}{...FORM_OPTIONS.item} >
                                        {data.country}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'updatePanel.data.province',
                                        defaultMessage: '省份'
                                    })}{...FORM_OPTIONS.item} >
                                        {data.province}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'updatePanel.data.city',
                                        defaultMessage: '城市'
                                    })}{...FORM_OPTIONS.item} >
                                        {data.city}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'updatePanel.data.contactNumber',
                                        defaultMessage: '联系电话'
                                    })}{...FORM_OPTIONS.item} >
                                        {data.contactNumber}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'updatePanel.data.fax',
                                        defaultMessage: '传真'
                                    })}{...FORM_OPTIONS.item} >
                                        {data.fax}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'updatePanel.data.address',
                                        defaultMessage: '联系地址'
                                    })}{...FORM_OPTIONS.item} >
                                        {data.address}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'updatePanel.data.zipCode',
                                        defaultMessage: '邮政编码'
                                    })}{...FORM_OPTIONS.item} >
                                        {data.zipCode}
                                    </FormItem>
                                </Col>
                            </Row>
                        </Card>
                        <Card
                            title={formatMessage({
                                id: 'updatePanel.partInformationDetail',
                                defaultMessage: '备件经营权限清单'
                            })}>
                            <Button
                                type="dashed"
                                icon="plus"
                                block
                                className={styles.plusBtn}
                                onClick={this.onClickAddDetailBtn}>
                                {formatMessage({
                                    id: 'updatePanel.operation.new',
                                    defaultMessage: '新增'
                                })}
                            </Button>
                            <Table
                                className="white-space-nowrap"
                                columns={partInformationColumns}
                                rowKey="id"
                                pagination={false}
                                dataSource={dealerParts}
                                {...TABLE} />
                        </Card>
                        <Card
                            title={formatMessage({
                                id: 'updatePanel.bank',
                                defaultMessage: '开户银行清单'
                            })}
                            extra={<Button size="small" onClick={this.onClickSearchBankBtn}>
                                {this.props.intl.formatMessage({
                                    id: 'updatePanel.bank.addDetail',
                                    defaultMessage: '新增清单'
                                })}</Button>}>
                            <Table
                                className="white-space-nowrap"
                                columns={bankColumns}
                                rowKey="bankId"
                                pagination={false}
                                dataSource={dealerBanks}
                                {...TABLE} />
                        </Card>
                        <Card
                            title={<Row>
                                <Col span={6}>
                                    {this.props.intl.formatMessage({
                                        id: 'updatePanel.parts',
                                        defaultMessage: '总代可提报备件清单'
                                    })}
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={this.props.intl.formatMessage({
                                        id: 'updatePanel.form.searchPartCode',
                                        defaultMessage: '备件号'
                                    })}
                                    {...FORM_OPTIONS.item}>
                                        <Search
                                            onSearch={this.onSearchClaim}
                                            value={this.state.searchPartCode}
                                            allowClear
                                            onChange={this.onChangeCodeValue}
                                            className={styles.minScreenSearchWidth}/>
                                    </FormItem>
                                </Col>
                            </Row>}
                            extra={<div>
                                {
                                    parts.length > 0 && <Export size="small" key={'export'} exportRequest={() => this.props.onClickDetailExport({
                                        id: data.id,
                                        isClearPart,
                                        parts: updateParts
                                    })} />
                                }
                                <Button size="small" onClick={this.onClickImportBtn}>
                                    {formatMessage({
                                        id: 'newPanel.operation.importDetail',
                                        defaultMessage: '增量导入'
                                    })}
                                </Button>
                                <Button size="small" onClick={this.onClickSearchPartBtn}>
                                    {this.props.intl.formatMessage({
                                        id: 'updatePanel.part.addDetail',
                                        defaultMessage: '新增清单'
                                    })}</Button></div>}>
                            <Table
                                className="white-space-nowrap"
                                columns={partColumns}
                                rowKey="partId"
                                dataSource={isSearch ? newParts : parts}
                                pagination={detailPagination}
                                onChange={this.onChangeDetail}
                                loading={this.state.loading}
                                {...TABLE} />
                        </Card>
                    </Form>
                    <Card>
                        <Row>
                            <Col className="col-align-right">
                                <Button key="submit"
                                    onClick={this.onSubmit}
                                    type="primary"
                                    loading={this.state.loading}>
                                    {formatMessage({
                                        id: 'addPanel.btn.submit',
                                        defaultMessage: '保存'
                                    })}</Button>
                            </Col>
                        </Row>
                    </Card>
                </Spin>
                {
                    this.state.showBankSelectPanel &&
                    <BankSelectPanel
                        selectKey={data.dealerId}
                        onCancel={this.onCloseBankSelectPanel}
                        onSelect={this.onSelectAddedBank} />
                }
                {
                    this.state.showPartSelectPanel &&
                    <PartSelectPanel
                        selectKey={data.dealerId}
                        onCancel={this.onClosePartSelectPanel}
                        onSelect={this.onSelectAddedPart} />
                }
                {
                    this.state.showDealerSelectPanel &&
                    <DealerSelectPanel
                        selectKey={data.dealerId}
                        onCancel={this.onCloseDealerSelectPanel}
                        onSelect={this.onSelectDealer} />
                }
                {
                    this.state.showImportPanel &&
                        <ImportPanel
                            selectKey={data.dealerId}
                            onCancel={this.onCloseImportPanel}
                            onImportChange={this.onImportChange} />
                }
                <div className="page-toolbar">
                    <Return
                        onConfirm={this.onClickReturnBtn}
                        disabled={this.state.loading}
                        showWarning={this.state.hasOperat} />
                </div>
            </div>
        );
    }
}

UpdatePanel.propTypes = {
    successReturn: PropTypes.func.isRequired,
    onCancel: PropTypes.func.isRequired,
    onClickDetailExport: PropTypes.func.isRequired,
    initEnumData: PropTypes.object,
    intl: PropTypes.object,
};

import {connect} from 'react-redux';
import {tableSearch, detailExport} from './actions';

import {createSelector} from 'reselect';
const getinitEnumData = createSelector(
    state => state.getIn(['page', 'domainData', 'initData']),
    init => {
        const initData = init.toJS();
        const brands = initData.brands ? initData.brands.map(item => ({
            text: `(${item.brandCode}) ${item.brandName}`,
            value: item.brandId
        })) : [];
        const tradeMethods = initData.tradeMethods ? initData.tradeMethods.map(item => ({
            text: `(${item.tradeMethodCode}) ${item.tradeMethodName}`,
            value: item.tradeMethodId
        })) : [];
        return {
            brands,
            tradeMethods,
            initData
        };
    }
);
const mapStateToProps = state => ({
    initEnumData: getinitEnumData(state),
});

const mapDispatchToProps = (dispatch, props) => ({
    onClickDetailExport: data => dispatch(detailExport(data)),
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(UpdatePanel));
